import com.sun.source.tree.WhileLoopTree;
import org.w3c.dom.ls.LSInput;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-02-05
 * Time: 21:47
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        //存储左孩子节点的引用
        public TreeNode left;
        //存储右孩子节点的引用
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
    //非递归前序遍历
    public void preOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;

        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
        System.out.println();
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }
    //非递归中序遍历
    public void inOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;

        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
        System.out.println();
    }

    //后序遍历
    public void postOrder(TreeNode root) {

        if (root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }
    //后序遍历非递归
    public void postOrderNor(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev= null;
        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if (top.right == null || top.right == prev){
                stack.pop();
                System.out.print(top.val+" ");
                prev = top;
            }else {
                cur = top.right;
            }
        }
        System.out.println();
    }

    public int countNode = 0;

    public void nodeSize(TreeNode root) {
        if (root == null) {
            return;
        }
        countNode++;
        nodeSize(root.left);
        nodeSize(root.right);
    }

    public int nodeSize2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return nodeSize2(root.left) + nodeSize2(root.right) + 1;
    }

    //求叶子节点个数
    //子问题：左树的叶子 + 右树的叶子 = 整棵树的叶子节点   递推公式
    //什么是叶子：既没有左子树 又 没有右子树 此时这个节点叫做叶子节点
    public int getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return 0;
        } else if (root.left == null && root.right == null) {
            return 1;
        } else {
            return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
        }
    }

    public int leafCount = 0;

    public void getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.right == null && root.left == null) {
            leafCount++;
        }
        getLeafNodeCount2(root.right);
        getLeafNodeCount2(root.left);
    }

    //第k层节点的个数
    public int getKLeveNodeSize(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLeveNodeSize(root.left, k - 1) +
                getKLeveNodeSize(root.right, k - 1);
    }

    //获取二叉树的高度
    //时间复杂度O（n）
    //空间复杂度O（log2 n）
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return leftH > rightH ? leftH + 1 : rightH + 1;
    }

    //在root这棵树中找val值
    //时间复杂度O（n）
    public TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }

        if (root.val == val) {
            return root;
        }

        TreeNode leftValue = find(root.left, val);
        if (leftValue != null) {
            return leftValue;
        }

        TreeNode rightValue = find(root.right, val);
        if (leftValue != null) {
            return rightValue;
        }

        return null;
    }

    //交换左右节点
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left == null && root.right == null){
            return root;
        }

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //平衡二叉树(普通版)
    //时间复杂度 O（N^2）
    public boolean isBalanced(TreeNode root){
        if (root == null){
            return true;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);

        return Math.abs(leftHeight-rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }
    public int maxDepth(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);
        return Math.max(leftH,rightH)+1;
    }

    //平衡二叉树（升级版）
    //时间复杂度O（n）
    public boolean isBalance1(TreeNode root){
        if (root == null){
            return true;
        }
        return maxDepth1(root) >= 0;
    }
    public int maxDepth1(TreeNode root){
        if (root == null){
            return 0;
        }
        int leftH = maxDepth1(root.left);
        if (leftH == -1){
            return -1;
        }
        int rightH = maxDepth1(root.right);
        if (leftH >= 0 && rightH >= 0
                && Math.abs(leftH-rightH)<=1){
            return Math.max(leftH,rightH)+1;
        }else {
            //证明高度差是>=2,不平衡
            return -1;
        }
    }

    //判断是否对称
    public boolean isSymmetric(TreeNode root){
        if (root == null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if ((leftTree == null && rightTree != null)||(leftTree != null && rightTree == null)){
            return false;
        }
        if (leftTree == null && rightTree == null){
            return true;
        }
        if (leftTree.val != rightTree.val){
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }

    //层序遍历
    public void levelOrder(TreeNode root){
        if (root == null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (queue != null){
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if (cur.left != null){
                queue.offer(cur.left);
            }
            if (cur.right != null){
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }

    public List<List<Character>> leveOrder2(TreeNode root){
        List<List<Character>> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            //一层的数据
            List<Character> curList = new ArrayList<>();
            int size = queue.size();
            while (size != 0){
                TreeNode cur = queue.poll();
                curList.add(cur.val);
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(curList);
        }
        return ret;

    }

    public boolean isCompleteTree(TreeNode root){
        if (root == null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while ((!queue.isEmpty())){
            TreeNode cur = queue.poll();
            if (cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        //再次判断队列是不是里面都是null
        while (!queue.isEmpty()){
            TreeNode cur =queue.peek();
            if (cur == null){
                queue.poll();
            }else {
                return false;
            }
        }
        return true;
    }

    //二叉树的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
        if (root == null){
            return null;
        }

        if (root == p || root == q){
            return root;
        }

        TreeNode leftT = lowestCommonAncestor(root.left,p,q);
        TreeNode rightT = lowestCommonAncestor(root.right,p,q);

        if (leftT != null && rightT != null){
            return root;
        }else if (leftT != null){
            return leftT;
        }else if (rightT != null){
            return rightT;
        }
        return null;
    }

    //找到root到指定节点node路径上的所有节点，存储到stack当中
    public boolean getPath(TreeNode root, TreeNode node ,Stack<TreeNode> stack){
        if (root == null){
            return false;
        }
        stack.push(root);

        if (root == node){
            return true;
        }

        boolean flg = getPath(root.left,node,stack);
        if (flg){
            return true;
        }

        flg = getPath(root.right,node,stack);
        if (flg){
            return true;
        }
        stack.pop();
        return false;
    }

    //二叉树的最近公共祖先（进阶版）
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p,TreeNode q){
        if (root == null){
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,p,stack1);
        getPath(root,q,stack2);
        //上述代码已经能够求到root到指定节点路径上的所有节点
        int size1 = stack1.size();
        int size2 = stack2.size();
        int size = size1 - size2;
        if (size < 0){
            size = Math.abs(size);
            while (size != 0){
                stack2.pop();
                size--;
            }
        }else {
            while (size != 0){
                stack1.pop();
                size--;
            }
        }
        //两个栈的大小是一样的了
        while (!stack1.isEmpty() && !stack2.isEmpty()){
            if (stack1.peek() == stack2.peek()){
                return stack1.pop();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;
    }

    //知道前序遍历和中序遍历创建二叉树
//    public int preIndex = 0;
//    public TreeNode buildTree(int[] preorder,int[] inorder){
//        return buildTreeChild(preorder,inorder,0,inorder.length-1);
//    }
//    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend){
//        if (inbegin > inend){
//            return null;
//        }
//        TreeNode root = new TreeNode(preorder[preIndex]);
//        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
//        preIndex++;
//        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
//        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
//        return root;
//    }
//    private int findIndex(int[] inorder,int inbegin,int inend,int key){
//        for (int i = inbegin; i < inend; i++) {
//            if (inorder[i] == key){
//                return i;
//            }
//        }
//        return -1;
//    }


    //知道中序和后序创建二叉树
//    public int postIndex = 0;
//    public TreeNode buildTree(int[] inorder,int[] postorder){
//        postIndex = postorder.length-1;
//        return buildTreeChild(postorder,inorder,0,inorder.length-1);
//    }
//    public TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend){
//        if (inbegin > inend){
//            return null;
//        }
//        TreeNode root = new TreeNode(postorder[postIndex]);
//        int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);
//        postIndex--;
//        root.left = buildTreeChild(postIndex,inorder,inbegin,rootIndex-1);
//        root.right = buildTreeChild(postIndex,inorder,rootIndex+1,inend);
//        return root;
//    }
//    private int findIndex(int[] inorder,int inbegin,int inend,int key){
//        for (int i = inbegin; i < inend; i++) {
//            if (inorder[i] == key){
//                return i;
//            }
//        }
//        return -1;
//    }

    //根据二叉树创建字符串（前序遍历）
    public String tree2str(TreeNode root){
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode root,StringBuilder stringBuilder){
        if (root == null){
            return;
        }
        stringBuilder.append(root.val);
        //判断根的左子树
        if (root.left != null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if (root.right == null){
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        //判断右子树
        if (root.right != null){
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}
